<?php

/**
 * Static content controller.
 *
 * This file will render views from views/pages/
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.Controller
 * @since         CakePHP(tm) v 0.2.9
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
App::uses('CakeEmail', 'Network/Email');
App::uses('AppController', 'Controller');

/**
 * Static content controller
 *
 * Override this controller by placing a copy in controllers directory of an application
 *
 * @package       app.Controller
 * @link http://book.cakephp.org/2.0/en/controllers/pages-controller.html
 */
class PagesController extends AppController {

	/**
	 * Controller name
	 *
	 * @var string
	 */
	public $name = 'Pages';

	/**
	 * This controller does not use a model
	 *
	 * @var array
	 */
	public $uses = array('Reward', 'User', 'UserReward','Business');

	/**
	 * Displays a view
	 *
	 * @param mixed What page to display
	 * @return void
	 */
	public function home() {
		//debug($list = I18n::loadPo(APP . 'locale' . DS . 'fra/LC_MESSAGES/default.po'));
		$this->layout = 'default';
		$output = '';
		$segments = $colors = array();
		foreach ($this->Reward->getRewards() as $val) {
			$segments[] = array('text' => $val['Reward']['name']);
			$color = '#' . $val['Reward']['color'];
			$colors[] = $color;
			$output .= "<li style='color:{$color}'>{$val['Reward']['name']}</li>";
		}
		$this->set(compact('segments', 'colors', 'output'));
		$this->setPageTitle('Home page');
	}

	public function extract() {
		$list = I18n::loadPo(APP . 'locale' . DS . 'default.pot');
		$lines = array();
		foreach ($list as $key => $val) {
			if (!empty($key)) {
				$val = addcslashes($key, "\"\n");
				$lines[] = 'msgid "' . $val . '"';
				$lines[] = 'msgstr "' . $val . '"';
				$lines[] = '#: ----------------------------------';
			}
		}
		file_put_contents(APP . 'locale' . DS . 'default.ok.pot', implode("\n", $lines));
		exit();
	}

	public function login() {
	    if(AuthComponent::user()!=array()){
			$this->redirect('/giftcard');
		}
	    $businesses = $this->Business->find('all');
		$this->set('businesses',$businesses);
		if (!empty($this->data)) {
			$user = $this->User->find('first', array(
				'conditions' => array(
					'booking' => $this->data['User']['booking'],
					'last_name' => $this->data['User']['last_name'],
					'first_name' => $this->data['User']['first_name']
				)
			));
			if ($user) {
				unset($user['User']['password']);
				$this->Auth->login($user['User']);
				$this->redirect('/');
			} else {
				$this->setFlash(__('Numéro de réservation or Last name or First name is incorrect'));
			}
		}
		$this->setPageTitle('Business section for customer');
	}
	public function play() {
		$user = AuthComponent::user();
		if($user['role_id']){
			$this->redirect('/admin/users');
		}else{
			if($user==array()){
				$this->redirect('/');
			}else{
				$businesses = $this->Business->find('all');
				$amount = $this->User->find('first',array('conditions'=>array('id'=>$user['id'])));
				$this->set('businesses',$businesses);
				$this->set('amount',$amount['User']['amount']);
			}
				$this->set('user',$user);
			}
	}
	public function send() {
		$user = AuthComponent::user();
		if($user==array()){
			$this->redirect('/');
		}else{
			if (!empty($this->data)) {
				$name = '';
				$businesses = $this->Business->find('all',array('conditions'=>array('id'=>explode(",", $this->request->data['User']['id_award']))));
				$this->set(compact('businesses'));
				foreach($businesses  as $business):
					$name.=$business['Business']['name'].' - ('.$business['Business']['value'].' $), ';
				endforeach;
				//debug($name);exit;
				$amountHave = $this->User->find('first',array('conditions'=>array('id'=>$user['id'])));
				$amount = $amountHave['User']['amount']-$this->request->data['User']['num_select'];
				$this->User->updateAll(array('amount'=>$amount,'address_delivery' => "'".$this->request->data['User']['address_delivery']."'",
					'id_award' => "'".$this->request->data['User']['id_award']."'",
					'town' => "'".$this->request->data['User']['town']."'",
					'zipcode' => "'".$this->request->data['User']['zipcode']."'",
					'phone' => "'".$this->request->data['User']['phone']."'"),array('id'=>$user['id']));
				
				//send
				$idx = $this->Reward->generateValue();
				$rewards = $this->Reward->getRewards();
				$expired = Configure::read('AppConfig.RewardExpiredDay') * DAY;
				$data = array(
					//'reward_id' => $rewards[$idx]['Reward']['id'],
					'user_id' => $user['id'],
					'fullname'=> $this->request->data['User']['last_name'].' '.$this->request->data['User']['first_name'],
					'name' => $name,
					'expired' => time() + $expired,
					'created' => time()
				);
				$subject = Configure::read('AppConfig.RewardEmailSubject');
				$ccEmail = Configure::read('AppConfig.RewardEmail');
				$Email = new CakeEmail('default');
				$Email->to($this->request->data['User']['email'])
					->emailFormat(CakeEmail::MESSAGE_HTML)
					->from(Configure::read('AppConfig.EmailSender'))
					->cc($ccEmail)
					->subject($subject ? $subject : 'Giftcard result')
					->template('result', 'default')
					->viewVars(array(
						'model' => 'User',
						'data' => $data,
						'user' => $user));	
				$Email->send();	
			}else{
				$this->redirect('/giftcard');
			}
		}
	}
	public function play1() {
		$this->disableCache();
		$this->viewClass = 'Json';
		$idx = $this->Reward->generateValue();
		if (!isset($this->request->query['flag']) || $this->request->query['flag'] != 'try') {
			if (!$this->UserReward->isPlayable()) {
				exit("ERROR");
			}
			$user = AuthComponent::user();
			$rewards = $this->Reward->getRewards();
			$expired = Configure::read('AppConfig.RewardExpiredDay') * DAY;
			$data = array(
				'reward_id' => $rewards[$idx]['Reward']['id'],
				'user_id' => $user['id'],
				'name' => $rewards[$idx - 1]['Reward']['name'],
				'expired' => time() + $expired,
				'created' => time()
			);
			$this->UserReward->create();
			if (!$this->UserReward->save($data)) {
				exit("Save info error");
			}
			/* SEND EMAIL */
			$subject = Configure::read('AppConfig.RewardEmailSubject');
			$ccEmail = Configure::read('AppConfig.RewardEmail');
			$Email = new CakeEmail('default');
			$Email->to($user['email'])
					->emailFormat(CakeEmail::MESSAGE_HTML)
					->from(Configure::read('AppConfig.EmailSender'))
					->cc($ccEmail)
					->subject($subject ? $subject : 'Lucky drawl result')
					->template('result', 'default')
					->viewVars(array(
						'model' => 'User',
						'data' => $data,
						'user' => $user));
			//$Email->debug = true;
			if ($Email->send()) {
				$this->UserReward->saveField('is_sent', true);
			}
		}
		$this->set('_index', $idx);
		$this->set('_serialize', array('_index'));
	}

}
